use axum::Json;
use com::{ code, query, sea_orm::connect_db};
use sea_orm::{query::*, FromQueryResult, DbBackend};
use serde::{ Deserialize, Serialize };
use serde_json::json;
#[derive(Debug, Deserialize, Serialize, FromQueryResult)]
pub struct Data {}

pub async fn list() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let dbname = "information_schema";
    let conn = connect_db(dbname).await?;
    let stmt = Statement::from_string(
        DbBackend::MySql,
        r#"show databases"#);
    let resut = Data::find_by_statement(stmt).into_json().all(&conn).await;
    match resut {
        Ok(mut f) => {
            _ = f.retain(|v|{
                let x = v.as_object().unwrap();
                if let Some(t) = x.get("Database") {
                    let s = t.as_str().unwrap_or_default();
                    return s != "information_schema" && s != "performance_schema" && s != "sakila" && s != "mysql"
                }
                return true
            });
            return code::data(json!(f));
        },
        Err(e) => code::sys(e.to_string())
    }
}
pub async fn add(Json(body):Json<JsonValue>) -> Result<Json<JsonValue>, Json<JsonValue>>{
    let dbname = query::str(&body,"dbname")?;
    let database = query::str(&body,"database")?;
    let conn = connect_db(&dbname).await?;
    let stmt = Statement::from_string(
        DbBackend::MySql, 
        format!("create database {}", database )
    );
    code::send_ok( conn.execute(stmt).await )
}
pub async fn del(Json(body):Json<JsonValue>) -> Result<Json<JsonValue>, Json<JsonValue>>{
    let dbname = query::str(&body,"dbname")?;
    let database = query::str(&body,"database")?;
    let conn = connect_db(&dbname).await?;
    let stmt = Statement::from_string(
        DbBackend::MySql, 
        format!("drop database {}", database )
    );
    code::send_ok( conn.execute(stmt).await )
}